package com.zjdiepu.www.manage.view;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.BusinessExtrasCodeType;
import com.zjdiepu.www.base.enums.type.BusinessExtrasType;
import com.zjdiepu.www.base.enums.type.DataDicType;
import com.zjdiepu.www.base.enums.type.LoanBankType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.commpent.RedisObjectClient;
import com.zjdiepu.www.commpent.ViewScopeControllerHelper;
import com.zjdiepu.www.ibiz.base.IDpBaseDataDictionaryService;
import com.zjdiepu.www.ibiz.cache.ICachedDictionaryService;
import com.zjdiepu.www.ibiz.cw.ICwIncomeExpensesItemService;
import com.zjdiepu.www.ibiz.cw.ICwRefundCarService;
import com.zjdiepu.www.ibiz.cw.ICwRemitCarService;
import com.zjdiepu.www.ibiz.icbc.IOtherLoanLossProvisionService;
import com.zjdiepu.www.ibiz.system.IBaseRemitAccountService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessExtrasService;
import com.zjdiepu.www.ibiz.yw.IYwFeesSubService;
import com.zjdiepu.www.ibiz.yw.IYwFundApplyService;
import com.zjdiepu.www.model.base.dto.DpBaseDataDictionary;
import com.zjdiepu.www.model.base.dto.SimpleDataDictionary;
import com.zjdiepu.www.model.base.ext.DpBaseDataDictionaryExt;
import com.zjdiepu.www.model.cw.dto.CwRefundCar;
import com.zjdiepu.www.model.cw.dto.CwRemitCar;
import com.zjdiepu.www.model.cw.response.CwFundItem;
import com.zjdiepu.www.model.icbc.dto.OtherLoanLossProvision;
import com.zjdiepu.www.model.icbc.ext.OtherLoanLossProvisionExt;
import com.zjdiepu.www.model.system.dto.BaseRemitAccount;
import com.zjdiepu.www.model.yw.dto.YwBusinessCar;
import com.zjdiepu.www.model.yw.dto.YwBusinessExtras;
import com.zjdiepu.www.model.yw.dto.YwFundApply;
import com.zjdiepu.www.model.yw.response.YwBusinessDetail;
import com.zjdiepu.www.util.ExceptionHelper;

/**
 * 垫提车款Controller层<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年05月11日 20时36分<br/>
 * @since 1.0<br/>
 */
@Controller
@RequestMapping(value= "CwRemitCarViewController", produces="text/html;charset=UTF-8")
@Api(tags = {"垫提车款"}, produces="text/html;charset=UTF-8")
public class CwRemitCarViewController extends BaseController {
    @Resource
    private ICwRemitCarService cwRemitCarService;
    @Resource
    private ViewScopeControllerHelper viewScopeControllerHelper;
    @Resource
    private ICachedDictionaryService cachedDictionaryService;
    @Resource
    private IDpBaseDataDictionaryService dBaseDataDictionaryService;
    @Resource
    private IYwFeesSubService ywFeesSubService;
    @Resource
    private ICwIncomeExpensesItemService cwIncomeExpensesItemService;
    @Resource
    private IYwBusinessExtrasService ywBusinessExtrasService;
    @Resource
    private IYwFundApplyService ywFundApplyService;
    @Resource
    private IBaseRemitAccountService baseRemitAccountService;
    @Resource
    private ICwRefundCarService cwRefundCarService;
    @Resource
    private IOtherLoanLossProvisionService otherLoanLossProvisionservice;
    @Resource
    private RedisObjectClient redisObjectClient;
    
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: remitCarDetail <br/>
     * @Description: 垫提车款详情 <br/>
     * @param model
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "垫提车款详情", response = Boolean.class, httpMethod="GET", tags={"垫提车款"})
    @RequestMapping(value = "remitCarDetail", method = RequestMethod.GET)
    public String remitCarDetail(Model model, String id) {
    	if (StringUtils.isBlank(id)) {
			ExceptionHelper.thow(ResultFlagType.PARAM_EMPTY);
		}
    	model.addAttribute("loanBank", cachedDictionaryService.getValueNamesWithSpaceOption(DataDicType.REMIT_TYPE,"请选择..."));
    	model.addAttribute("fundChannel", cachedDictionaryService.getValueNamesWithSpaceOption(DataDicType.FUND_CHANNEL,"请选择..."));
    	model.addAttribute("remitFinanceAuditor", cachedDictionaryService.getValueNamesWithSpaceOption(DataDicType.FINANCE_AUDITOR,"请选择..."));
    	model.addAttribute("tjTransferAccno", cachedDictionaryService.getValueNamesWithSpaceOption(DataDicType.TJ_TRANSFER_ACCNO,"请选择..."));
    	
    	//常量
    	model.addAttribute("tjgsyh", LoanBankType.TIAN_JIN_GONG_SHAN_YIN_HANG.getCode());
    	
    	viewScopeControllerHelper.preparedNowTime(model);
    	YwBusinessDetail ywBusinessDetail = viewScopeControllerHelper.preparedBusiness(id, model);
    	if(ywBusinessDetail != null){
    		if("ICBC".equals(ywBusinessDetail.getLoanBank())){
        		model.addAttribute("prepare_account", true);
        		
        		//风险准备金
        		OtherLoanLossProvisionExt otherLoanLossProvisionExtParam = new OtherLoanLossProvisionExt();
        		otherLoanLossProvisionExtParam.setBaseWhere();
        		otherLoanLossProvisionExtParam.withOutPage();
        		List<OtherLoanLossProvision> otherLoanLossProvisions = otherLoanLossProvisionservice.selectByExt(otherLoanLossProvisionExtParam);
        		model.addAttribute("otherLoanLossProvisions", otherLoanLossProvisions);
        	}
    		
    		viewScopeControllerHelper.preparedYwFee(id, ywBusinessDetail.getCustomerId(), model);
    		CwRemitCar remitNotRefund = cwRemitCarService.getRemitNotRefund(id);
    		if(null != remitNotRefund) { //有未退款垫款时，展示
    			model.addAttribute("cwRemitCar",  remitNotRefund);
    			YwFundApply ywFundApply = ywFundApplyService.selectById(remitNotRefund.getFundApplyId());
    			model.addAttribute("ywFundApply",  ywFundApply);
    		} else {
    			YwFundApply applyNotRemit = ywFundApplyService.getApplyNotRemit(id);
    			model.addAttribute("ywFundApply",  applyNotRemit);
    		}
//    		viewScopeControllerHelper.preparedRemitCar(id, ywBusinessDetail.getCustomerId(), model);
    		viewScopeControllerHelper.preparedBuyer(id, model);
    		
    		Map<String, String> accountReceivers = CollectionInitUtil.emptyMap();
    		redisObjectClient.execute(new RedisCallback<Boolean>() {

				@Override
				public Boolean doInRedis(RedisConnection redisConnection)
						throws DataAccessException {
					
					List<SimpleDataDictionary> fundChannels = cachedDictionaryService.getCachedDataDics(DataDicType.FUND_CHANNEL);
					if(CollectionUtils.isNotEmpty(fundChannels)) {
						for(SimpleDataDictionary fundChannel : fundChannels) {
							BaseRemitAccount baseRemitAccount = baseRemitAccountService.queryBySalesmanId(ywBusinessDetail.getSalesmanId(), fundChannel.getValue());
							if(null == baseRemitAccount) {
								continue;
							}
							String bankId = baseRemitAccount.getBankId();
							SimpleDataDictionary bank = redisObjectClient.hGet(redisConnection, SimpleDataDictionary.class.getSimpleName(), bankId, DataDicType.BANK.getCode());
							accountReceivers.put(baseRemitAccount.getId(), fundChannel.getName() + ":" + bank.getName() + "-" + baseRemitAccount.getAccountName() + "-" + baseRemitAccount.getAccounnNo() );
						}
					}
					return true;
				}
			});
    		model.addAttribute("accountReceivers", accountReceivers);
    	}
    	
    	YwBusinessCar car = viewScopeControllerHelper.preparedCar(id,ywBusinessDetail.getCustomerId(), model);
    	if(car != null) {
    		viewScopeControllerHelper.preparedLoan(id, car.getId(), model, car.getCarType());
    	}
//    	viewScopeControllerHelper.preparedCarModel(model);
//    	获取费用数据字典=====================
    	DpBaseDataDictionaryExt dpBaseDataDictionaryExt = new DpBaseDataDictionaryExt();
    	dpBaseDataDictionaryExt.setBaseWhere();
    	dpBaseDataDictionaryExt.withOutPage();
    	dpBaseDataDictionaryExt.setParentValue(DataDicType.FUND_ITEM.getCode());
    	dpBaseDataDictionaryExt.setAddedValue1("01"); //启用的明细
    	dpBaseDataDictionaryExt.setOrderSql("`VALUE`");
//		只展示附加值为1的数据
    	List<DpBaseDataDictionary> dpBaseDataDictionarys = dBaseDataDictionaryService.selectByExt(dpBaseDataDictionaryExt);
    	
    	DpBaseDataDictionaryExt depositItemExt = new DpBaseDataDictionaryExt();
    	depositItemExt.setBaseWhere();
    	depositItemExt.setRows(1);
    	depositItemExt.setParentValue(DataDicType.FUND_ITEM.getCode());
    	depositItemExt.setValue("35");
    	List<DpBaseDataDictionary> depositDataDictionaryItems = dBaseDataDictionaryService.selectByExt(depositItemExt);
    	if(CollectionUtils.isNotEmpty(depositDataDictionaryItems)) {
    		dpBaseDataDictionarys.add(depositDataDictionaryItems.get(0));
    	} else {
    		DpBaseDataDictionary dpBaseDataDictionary = new DpBaseDataDictionary();
    		dpBaseDataDictionary.setValue("35");
    		dpBaseDataDictionary.setName("征信押金");
    		dpBaseDataDictionary.setParentValue(DataDicType.FUND_ITEM.getCode());
    		dpBaseDataDictionarys.add(dpBaseDataDictionary);
    	}
    	depositItemExt.setBaseWhere();
    	depositItemExt.setRows(1);
    	depositItemExt.setParentValue(DataDicType.FUND_ITEM.getCode());
    	depositItemExt.setValue("01");
    	List<DpBaseDataDictionary> depositDataDictionaryItems_ = dBaseDataDictionaryService.selectByExt(depositItemExt);
    	if(CollectionUtils.isNotEmpty(depositDataDictionaryItems_)) {
    		dpBaseDataDictionarys.add(depositDataDictionaryItems_.get(0));
    	} else {
    		DpBaseDataDictionary dpBaseDataDictionary = new DpBaseDataDictionary();
    		dpBaseDataDictionary.setValue("01");
    		dpBaseDataDictionary.setName("按揭服务费");
    		dpBaseDataDictionary.setParentValue(DataDicType.FUND_ITEM.getCode());
    		dpBaseDataDictionarys.add(dpBaseDataDictionary);
    	}
//    	获取费用数据字典=====================
    	
    	
//    	==================应收获取============================
    	List<Map<String, Double>> fees = ywFeesSubService.countReceiveByBusiId(id, null);
//    	==================应收获取============================
    	
//    	==================已收获取============================   	
    	List<String> exludeKeys = Arrays.asList(new String[]{"01", "35"});
    	List<CwFundItem> fundItems = CollectionInitUtil.emptyList();
    	List<CwFundItem> fundItems_ = CollectionInitUtil.emptyList();
    	List<Map<String, Double>> remits = cwIncomeExpensesItemService.countReceiveByBusiId(id, null);
    	if(CollectionUtils.isNotEmpty(dpBaseDataDictionarys)) {
    		for(DpBaseDataDictionary dpBaseDataDictionary : dpBaseDataDictionarys) {
    			CwFundItem cwFundItem = new CwFundItem();
    			String key = dpBaseDataDictionary.getValue();
    			cwFundItem.setKey(key);
    			cwFundItem.setName(dpBaseDataDictionary.getName());
    			cwFundItem.setFeeCount(ViewScopeControllerHelper.getItem(fees, key));
    			cwFundItem.setRemitCount(ViewScopeControllerHelper.getItem(remits, key));
    			if(exludeKeys.contains(key)) {
    				fundItems_.add(cwFundItem);
    			} else {
    				fundItems.add(cwFundItem);
    			}
    		}
    	}
//    	==================已收获取============================  
    	model.addAttribute("fundItems", fundItems);
    	model.addAttribute("fundItems_", fundItems_);
    	
    	CwFundItem cwFundItem = new CwFundItem();
    	cwFundItem.setFeeCount(ViewScopeControllerHelper.countItems(fees, null));
    	cwFundItem.setRemitCount(ViewScopeControllerHelper.countItems(remits, null));
    	model.addAttribute("fundTotal", cwFundItem);
    	
    	String history = cwRemitCarService.queryHistoryByBusiId(id);
    	model.addAttribute("history", StringUtils.isBlank(history)?"-":(history.startsWith(",")?history.substring(1):history));
    	
    	//特殊订单
		YwBusinessExtras ywBusinessExtras = new YwBusinessExtras();
		ywBusinessExtras.setDpStatus(DpStatus.NORMAL.getCode());;
		ywBusinessExtras.setCodeExtras(BusinessExtrasCodeType.IS_SPECIAL_ORDER.getCode());
		ywBusinessExtras.setTypeExtras(BusinessExtrasType.AUDIT.getCode());
		ywBusinessExtras.setBusiId(id);
		YwBusinessExtras ywBusinessExtras_ = ywBusinessExtrasService.selectRefined(ywBusinessExtras);
		boolean isSpecialOrder = false;
		if(null != ywBusinessExtras_) {
			if("1".equals(ywBusinessExtras_.getValueExtras())) {
				isSpecialOrder = true;
//				return ApiResponse.fail(999,"该订单被风控标注为特殊订单");
			}
		}
		model.addAttribute("isSpecialOrder", isSpecialOrder);
		
		CwRefundCar cwRefundCarParam = new CwRefundCar();
		cwRefundCarParam.setDpStatus(DpStatus.NORMAL.getCode());
		cwRefundCarParam.setBusiId(id);
		CwRefundCar cwRefundCar = cwRefundCarService.selectRefined(cwRefundCarParam);
		if(null != cwRefundCar) {
			model.addAttribute("hasRefunded", true);
			model.addAttribute("refundTimeArrive", cwRefundCar.getTimeArrive());
		}
    	
//    	SysUser sysUser =(SysUser)getCurrentUser();
//    	viewScopeControllerHelper.preparedAllocation(sysUser.getOrgId(), model);
    	
    	return "system/cw/remitCarDetail";
    }
}
